package SAX;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class Demo1 {
	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser sp = factory.newSAXParser();
		XMLReader reader = sp.getXMLReader();
		reader.setContentHandler(new MyContentHandler2());
		reader.parse("src/book1.xml");
	}

}

// 得到xml文档内容的事件处理器
class MyContentHandler implements ContentHandler {

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		System.out.println("当前解析到了内容： " + new String(ch, start, length));
	}

	@Override
	public void endDocument() throws SAXException {

	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		System.out.println("结束标签： " + qName);
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {

	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {

	}

	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {

	}

	@Override
	public void setDocumentLocator(Locator locator) {

	}

	@Override
	public void skippedEntity(String name) throws SAXException {

	}

	@Override
	public void startDocument() throws SAXException {

	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		System.out.println("开始标签： " + qName);
		int len = atts.getLength();
		for (int i = 0; i < len; i++) {
			String attname = atts.getQName(i);
			String attvalue = atts.getValue(i);
			System.out.println(attname + " = " + attvalue);
		}
	}

	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {

	}

}

// 用于获取指定节点内容
class MyContentHandler2 extends DefaultHandler {
	private boolean isSell = false;
    private int index=1;
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (isSell&&index==1) {
			System.out.println("当前解析到了售价： " + new String(ch, start, length));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.compareTo("售价") == 0) {
			isSell = false;
			index++;
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.compareTo("售价") == 0) {
			isSell = true;
		}

	}

}
